package com.beyondsoft.common.core.sys.aop;

import com.beyondsoft.common.core.constant.TransactionConstants;
import com.beyondsoft.common.core.exchange.sender.SubToMainSender;
import com.beyondsoft.common.core.redis.RedisMsService;
import com.beyondsoft.common.core.sys.controller.CheckLoginController;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class SubscribeAop {

    @Autowired
    private RedisMsService redisMsService;
    @Autowired
    private SubToMainSender subToMainSender;

    @Pointcut("execution(public * com.beyondsoft.*.controller.*Controller.*(..))")
    private void controllerMethod() {
    }

    @Around("controllerMethod()")
    public Object controllerAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // start stopwatch   相当于是before advice
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //remote request注册事务组
        String thread = request.getHeader("thread");
        String packageKey = null;
        if (thread != null) {
            //remote redis key
            packageKey = TransactionConstants.PACKAGEKEY + thread + ":" + request.getMethod() + "-" + request.getRequestURI();
            //初始化线程事务状态
            redisMsService.set(packageKey, TransactionConstants.PACKAGEKEY_STATUS_INIT);
        }

        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            token = request.getHeader("token");
        }

        if (proceedingJoinPoint.getTarget() instanceof CheckLoginController) {
            CheckLoginController checkLoginController = (CheckLoginController) proceedingJoinPoint.getTarget();
            checkLoginController.load(token);
        }

        Object retVal = proceedingJoinPoint.proceed();
        // stop stopwatch    相当于是after advice

        return retVal;
    }

}
